import { create } from 'zustand';

export interface ModalConfig {
  id: string;
  title: string;
  content: string;
  type?: 'info' | 'warning' | 'error' | 'confirm';
  confirmText?: string;
  cancelText?: string;
  onConfirm?: () => void | Promise<void>;
  onCancel?: () => void;
  showCancel?: boolean;
  loading?: boolean;
}

interface ModalState {
  modals: ModalConfig[];
  showModal: (config: Omit<ModalConfig, 'id'>) => string;
  updateModal: (id: string, updates: Partial<ModalConfig>) => void;
  closeModal: (id: string) => void;
  closeAllModals: () => void;
}

export const useModalStore = create<ModalState>(set => ({
  modals: [],

  showModal: config => {
    const id = Math.random().toString(36).substr(2, 9);
    const modal: ModalConfig = {
      ...config,
      id,
      type: config.type ?? 'confirm',
      confirmText: config.confirmText ?? '确认',
      cancelText: config.cancelText ?? '取消',
      showCancel: config.showCancel ?? true,
      loading: false,
    };

    set(state => ({
      modals: [...state.modals, modal],
    }));

    return id;
  },

  updateModal: (id, updates) => {
    set(state => ({
      modals: state.modals.map(modal => (modal.id === id ? { ...modal, ...updates } : modal)),
    }));
  },

  closeModal: id => {
    set(state => ({
      modals: state.modals.filter(modal => modal.id !== id),
    }));
  },

  closeAllModals: () => {
    set({ modals: [] });
  },
}));

// 便捷的 modal 函数
export const modal = {
  confirm: (config: {
    title: string;
    content: string;
    onConfirm?: () => void | Promise<void>;
    onCancel?: () => void;
    confirmText?: string;
    cancelText?: string;
  }) => {
    return useModalStore.getState().showModal({
      ...config,
      type: 'confirm',
    });
  },

  info: (config: {
    title: string;
    content: string;
    onConfirm?: () => void;
    confirmText?: string;
  }) => {
    return useModalStore.getState().showModal({
      ...config,
      type: 'info',
      showCancel: false,
    });
  },

  warning: (config: {
    title: string;
    content: string;
    onConfirm?: () => void | Promise<void>;
    onCancel?: () => void;
    confirmText?: string;
    cancelText?: string;
  }) => {
    return useModalStore.getState().showModal({
      ...config,
      type: 'warning',
    });
  },

  error: (config: {
    title: string;
    content: string;
    onConfirm?: () => void;
    confirmText?: string;
  }) => {
    return useModalStore.getState().showModal({
      ...config,
      type: 'error',
      showCancel: false,
    });
  },
};
